package com._54programer.ws;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com._54programer.ws.handler.WsServerHandler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyComm {

	private static Map<String, Set<String>> groups = WsServerHandler.groups;
	private static Map<String, Channel> users = WsServerHandler.users;

	public static void bindGroup(ChannelHandlerContext ctx, String groupId) {
		if (groups.containsKey(groupId)) {
			groups.get(groupId).add(ctx.channel().id().asShortText());
		} else {
			Set<String> cid = new HashSet<String>();
			cid.add(ctx.channel().id().asShortText());
			groups.put(groupId, cid);
		}
	}

	public static void unbindGroup(ChannelHandlerContext ctx, String groupId) {
		if (groups.containsKey(groupId)) {
			groups.get(groupId).remove(ctx.channel().id());
		}
	}

	public static void bindUser(ChannelHandlerContext ctx, String user) {
		if (!users.containsKey(user)) {
			users.put(user, ctx.channel());
		}
	}

	public static void unbindUser(ChannelHandlerContext ctx, String user) {
		if (users.containsKey(user)) {
			users.remove(user);
		}
	}

	public static void sendByGroup(String groupId, String message) {
		if (groups.containsKey(groupId)) {
			for (Channel channel : WsServerHandler.clients) {
				for (String cid : groups.get(groupId)) {
					if (channel.id().asShortText().equals(cid)) {
						WsServerHandler.clients.find(channel.id()).writeAndFlush(new TextWebSocketFrame(message));
					}
				}
			}
		}
	}

	public static void sendByUser(String user, String message) {
		if (users.containsKey(user)) {
			users.get(user).writeAndFlush(new TextWebSocketFrame(message));
		}
	}

	public static void sendAll(String message) {
		ChannelGroup clients = WsServerHandler.clients;
		clients.writeAndFlush(new TextWebSocketFrame(message));
	}

	public static void send(ChannelHandlerContext ctx, String message) {
		ctx.writeAndFlush(new TextWebSocketFrame(message));
	}

}
